<?php

namespace application\diyform\controller;

use application\admin\controller\base as auth;
use ticky\request;
use ticky\page;

class index extends auth {

    public $modelid, $modelinfo;

    function __construct() {
        parent::__construct();
        $this->modelid = isset($_GET['modelid']) ? intval($_GET['modelid']) : (isset($_POST['modelid']) ? intval($_POST['modelid']) : 0);
        if (ACTION_NAME != 'index')
            $this->_check_model();
    }

    /**
     * 自定义表单列表
     */
    public function index() {
        $model = db('model');
        $total = $model->where(array('type' => 1, 'disabled' => 0))->total();
        $page = new page($total, 10);
        $formdata = $model->where(array('type' => 1, 'disabled' => 0))->order('modelid DESC')->limit($page->limit())->select();

        //SEO相关设置
        $site = get_config();
        $seo_title = '自定义表单列表_' . $site['site_name'];
        $keywords = $site['site_keyword'];
        $description = $site['site_description'];
        $pages = '<span class="pageinfo">共' . $total . '条记录</span>' . $page->total();

        $this->display('list_diyform', 'home');
    }

    /**
     * 自定义表单显示页
     */
    public function show() {
        $modelid = $this->modelid;
        $modelinfo = $this->modelinfo;
        $title = $modelinfo['name'];
        $template = $modelinfo['show_template'];

        $fieldstr = $this->_get_model_str($modelid);
        $field_check = $this->_get_model_str($modelid, true);

        $this->assign('title', $title);
        $this->assign('modelid', $modelid);
        $this->assign('modelinfo', $modelinfo);
        $this->assign('fieldstr', $fieldstr);
        $this->assign('field_check', $field_check);

        $this->display($template, 'home');
    }

    /**
     * 自定义表单提交
     */
    public function post() {
        if (request::isPost()) {
            //检查是否开启验证码
            if ($this->modelinfo['check_code']) {
                $code = request::post('code', '');
                $captcha = captcha::instance()->check(CONTROLLER_NAME, $code);
                if ($captcha['code'] != 200) {
                    showmsg(L('code_error'));
                }
            }
            //检查必填
            $field_check = $this->_get_model_str($this->modelid, true);
            foreach ($field_check as $k => $v) {
                if ($v['isrequired']) {
                    if (empty($_POST[$k]))
                        showmsg($v['errortips']);
                }
            }

            foreach ($_POST as $_k => $_v) {
                $_POST[$_k] = !is_array($_POST[$_k]) ? new_html_special_chars(trim_script($_v)) : $this->_content_dispose($_v);
            }

            $_POST['uid'] = session('uid');
            $_POST['inputtime'] = TIMESTAMP;

            $id = db($this->modelinfo['tablename'])->insert($_POST);

            if (!$id) {
                showmsg(L('operation_failure'), 'stop');
            }
            db('model')->where(['modelid' => $this->modelid])->update(array('items' => 'items+1'));
            //发送邮件通知

            showmsg(L('operation_success'));
        }
    }

    /**
     * 检查model
     */
    private function _check_model() {

        $data = db('model')->where(array('modelid' => $this->modelid))->find();
        if (!$data || $data['type'] != 1 || $data['disabled'] == 0) {
            showmsg('表单不存在或已禁用!', 'stop');
        }

        $setting = json_decode($data['setting'], true);

        if (!$setting['allowvisitor'] && empty(session('uid')))
            showmsg('请登录会员！', url_referer(get_url()), 2);

        $this->modelinfo = array_merge($data, $setting);
    }

    /**
     * 获取不同模型获取HTML表单
     */
    private function _get_model_str($modelid, $field = false, $data = array()) {
        load_extend('form.class.php');
        $modelinfo = cache($modelid . '_model');
        if ($modelinfo === false) {
            $modelinfo = db('model_field')->where(array('modelid' => $modelid, 'disabled' => 1))->order('listorder ASC, field ASC')->select();
            cache($modelid . '_model', $modelinfo);
        }

        $fields = $fieldstr = array();
        foreach ($modelinfo as $val) {
            $fieldtype = $val['fieldtype'];
            if ($data) {
                $val['defaultvalue'] = isset($data[$val['field']]) ? $data[$val['field']] : '';
            }
            $setting = $val['setting'] ? string2array($val['setting']) : 0;
            $required = $val['isrequired'] ? '<span class="red">*</span>' : '';
            //runlog('debug', 'form:' . $fieldtype . $setting);
            $fieldstr[] = '<td class="title">' . $val['name'] . $required . '</td><td>' . \form::$fieldtype($val['field'], $val['defaultvalue'], $setting) . '</td>';
            $fields[$val['field']] = $val['isrequired'] ? array('isrequired' => 1, 'fieldtype' => $fieldtype, 'errortips' => $val['errortips'] ? $val['errortips'] : $val['name'] . '不能为空！') : array('isrequired' => 0);
        }

        return $field ? $fields : $fieldstr;
    }

    /**
     * 内容处理
     * @param $content
     */
    private function _content_dispose($content) {
        $is_array = false;
        foreach ($content as $val) {
            if (is_array($val))
                $is_array = true;
            break;
        }
        if (!$is_array) {
            return safe_replace(implode(',', $content));
        }
        //这里认为是多文件上传
        $arr = array();
        foreach ($content['url'] as $key => $val) {
            $arr[$key]['url'] = safe_replace($val);
            $arr[$key]['alt'] = safe_replace($content['alt'][$key]);
        }
        return array2string($arr);
    }

}
